package ljl.alg.jianzhioffer.round2;

import commons.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 所有从根节点到叶节点等于目标值的路径
 * 这就是个简单回溯，感觉不难
 *
 * */
public class _34_path_sum {
   
    /**
     * 蒙过了。。
     * */
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int target) {
        dfs(root, new ArrayList<>(), 0, target);
        return res;
    }
    void dfs(TreeNode root, List<Integer> path, int sum, int target) {
        if (root == null) {
            return;
        }
        path.add(root.val);
        if (root.left == null && root.right == null && sum + root.val == target) {
            res.add(new ArrayList<>(path));
            path.remove(path.size() - 1);
            return;
        }
        dfs(root.left, path, sum + root.val, target);
        dfs(root.right, path, sum + root.val, target);
        path.remove(path.size() - 1);
    }
    
    class lufei {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        public List<List<Integer>> pathSum(TreeNode root, int target) {
            dfs(root, target);
            return res;
        }
        void dfs(TreeNode root, int target) {
            if (root == null) {
                return;
            }
            target -= root.val;
            path.add(root.val);
            if (target == 0 && root.left == null && root.right == null) {
                res.add(new ArrayList<>(path));
                path.remove(path.size() - 1);
                return;
            }
            dfs(root.left, target);
            dfs(root.right, target);
            path.remove(path.size() - 1);
        }
    }
}
